import { DbResource } from './dbResource.model';
import { Injectable } from '@nestjs/common';
import { InjectModel } from '@nestjs/sequelize';
import { Op } from "sequelize";
import { RESPONSE_CODE } from '@/enums/code';
import { getPageWhere, getPageData } from '@/utils/page';
import { GetDbResourcePageDto, AddDbResourceDto, UpdateDbResourceDto } from './dbResource.dto';


@Injectable()
export class DbResourceService {
  constructor(
    @InjectModel(DbResource)
    private dbResourceModel: typeof DbResource,

  ) { }


  /**
   * 获取数据库资源分页
   * @method get
   * @param getDbResourcePageDto
   */
  async getDbResourcePage(getDbResourcePageDto: GetDbResourcePageDto) {
    const { name, classify, code, current, size } = getDbResourcePageDto

    let query = {};
    if (name) {
      query["name"] = { [Op.like]: `${name}%` };
    }
    if (classify) {
      query["classify"] = classify;
    }

    if (code) {
      query["code"] = { [Op.like]: `${code}%` };
    }

    const { count, rows } = await this.dbResourceModel.findAndCountAll({
      where: query,
      ...getPageWhere(current, size)
    });

    return {
      code: RESPONSE_CODE.SUCCESS,
      data: getPageData(current, size, count, rows),
      msg: null,
    }
  }

  /**
   * 添加数据库资源
   * @method post
   * @param 
   */
  async addDbResource(addDbResourceDto: AddDbResourceDto) {
    await this.dbResourceModel.create({
      ...addDbResourceDto
    });
    return {
      code: RESPONSE_CODE.SUCCESS,
      data: null,
      msg: null,
    }
  }

  /**
   * 更新数据库资源
   * @method post
   * @param 
   */
  async updateDbResource(updateDbResourceDto: UpdateDbResourceDto) {
    await this.dbResourceModel.update({
      ...updateDbResourceDto
    }, {
      where: { id: updateDbResourceDto.id },
    });
    return {
      code: RESPONSE_CODE.SUCCESS,
      data: null,
      msg: null,
    }
  }

  /**
   * 删除数据库资源
   * @method post
   * @param id
   */
  async deleteDbResource(id: number) {
    await this.dbResourceModel.destroy({
      where: { id },
    });
    return {
      code: RESPONSE_CODE.SUCCESS,
      data: null,
      msg: null,
    }
  }

  /**
   * 获取数据库资源详情
   * @method get
   * @param id
   */
  async getResourceInfo(id: number) {
    const info = await this.dbResourceModel.findOne({
      where: { id },
    });
    return {
      code: RESPONSE_CODE.SUCCESS,
      data: info,
      msg: null,
    }
  }
}
